package com.jvup.common.widget;

import android.view.View;
import android.view.View.OnAttachStateChangeListener;

public class ReferBinder<T extends View> {

    private T view;

    private final OnAttachStateChangeListener detachedFromWindowListener = new OnAttachStateChangeListener() {
        @Override
        public void onViewAttachedToWindow(View v) { }
        @Override
        public void onViewDetachedFromWindow(View v) { destroy(); }
    };

    public final void bindView(T view) {
        if(view == null) {
            return;
        }
        this.view = view;
        this.view.addOnAttachStateChangeListener(detachedFromWindowListener);
        onBindView(view);
    }

    public final void destroy() {
        if(view == null) {
            return;
        }
        onDestroy(this.view);
        this.view.removeOnAttachStateChangeListener(detachedFromWindowListener);
        this.view = null;
    }

    public T get() {
        return view;
    }

    protected void onBindView(T view) {

    }
    protected void onDestroy(T view) {

    }

}
